$(function() {
    jQuery.metadata.setType("attr", "validate");
    
    $("#btnPromotionSave").click(function() {
        savePromotionTag();
    });

    $("#btnPromotionBack").click(function() {
        //window.location.href = rootPath + "/promotion/listpromotionTagPage";
        window.location.href = rootPath + "/productTag/toListProductTagPage?tabIndex=2";
    });
    
    initFancyBoxImg('image');
});

function doCheck() {
    var promotionTagFormValidator = $(document.promotionTagForm).validate(validateOptions);
    var vali = promotionTagFormValidator.form();
    if(!vali) {
        return false;
    }
    return true;
}

var validateOptions = {
    rules : {
        tagName : {
            required : false,
            minlength : 0,
            maxlength : 50
        }
    },
    messages : {
        tagName : {
            required : '请填写标签名称',
            minlength : '标签名称至少3个字符',
            maxlength : '标签名称至少50个字符'
        }
    },
    errorPlacement : function(error, element) { // 错误信息位置设置方法
        var tagName = $(element).is("select");
        if (!tagName) {
            error.insertAfter(element);
        } else {
            error.insertAfter(element.parent().next());
        }
    },
    submitHandler : function(form) {
        form.submit();
    }

};

function savePromotionTag() {
    if(doCheck()) {
        $.ajax({
            url : rootPath + "/promotionTag/savePromotionTag",
            type : "post",
            async : false,
            dataType : 'json',
            data : {
                id : $("#id").val(),
                tagName : $("#tagName").val(),
                tagIcon : $("#tagIcon").val()
            },
            success : function(json) {
                if(json.code == '1') {
                    showSuccess(json.msg, function() {
                        //window.location.href = rootPath + "/promotionTag/toListPromotionTagPage";
                        window.location.href = rootPath + "/productTag/toListProductTagPage?tabIndex=2";
                    });
                } else {
                    showErr(json.msg);
                }
            }
        });
    }
}


//************************************************上传图片所需的函数BEGIN********************************************************//
/**
* 通过ajax提交图片
*/
function ajaxFileUpload(obj, tag) {
	var image_container = $(obj).parents(".image_container");
	var lis = image_container.find("li");
	if (lis.length > 1) {
		msg("只能上传一张照片");
		return false;
	}
	var check = imageCheck(obj);
	if (!check) {
		return;
	}
	var id = $(obj).attr("id");
	//loading层
	var index = layer.msg('上传中...', {
		icon : 16,
		shade : 0.01,
		time : 0
	});
	$.ajaxFileUpload({
		url : rootPath + '/uploadFile/uploadOneFile',
		secureuri : false,
		fileElementId : id, // input标签id属性值
		dataType : 'json',
		success : function(data) {
			layer.close(index);
			if (data.code == 1) {
				$("#tagIcon").val(data.filePath);
				var oldLi = 
						"<li>"
						+ "	<div class=\"pic1\">"
						+ "		<img src=\"" + rootPath + "/statics/images/upload_pic1.png\" />"
						+ "		<input id=\""+id+"\" type=\"file\" name=\"uploadImage\" onchange=\"ajaxFileUpload(this,'"+tag+"')\" />"
						+ "</div>" 
						+ "</li>";
				var li = "<li>" 
						+ " <div class=\"pic1\">" 
						+ "		<a rel='"+tag+"' href='" + imgRootURL + data.filePath + "'>" 
						+ "			<img src=\"" + imgRootURL + data.filePath + "?x-oss-process=image/resize,h_60/format,png\" />"
						+ "		</a>"
						+ "		<a href=\"javascript:void(0)\" class=\"icon_close\"></a>"
						+ " </div>" 
						+ "</li>";
				image_container.empty().append(li);
				image_container.find("a[class='icon_close']").each(function() {
					//左上角删除按钮点击事件
					$(this).click(function() {
						$(this).closest("li").remove();
						image_container.append(oldLi);
						image_container.next().val("");
					});
				});
				//加载大图查看
				initFancyBoxImg(tag);
			} else {
				msg("上传失败");
			}
		},
		error : function(data, status, e) {
			layer.close(index);
			console.log(e);
			console.log(status);
			console.log(data);
			msg("系统异常");
		}
	});
}
/**
* 关闭图片 
*/ 
function clearImage(_this, tag) {
	var id = "upload_image";
	var oldLi = 
		"<li>"
		+ "	<div class=\"pic1\">"
		+ "		<img src=\"" + rootPath + "/statics/images/upload_pic1.png\" />"
		+ "		<input id=\""+id+"\" type=\"file\" name=\"upload_image\" onchange=\"ajaxFileUpload(this,'"+tag+"')\" />"
		+ "</div>" 
		+ "</li>";
	var image_container = $(_this).parents(".image_container");
	image_container.empty().append(oldLi);
	image_container.next().val("");
}

//检查图片格式及大小
function imageCheck(obj){
	var id = $(obj).attr("id");
	var filePath = $("#"+id).val();
	//检查后缀
	var ext = filePath.substring(filePath.lastIndexOf("."), filePath.length).toUpperCase();
	if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") {
		layer.msg('只能上传图片',{time:500});
		return false;
	}
	var file_size = 0;
	if (false || !!document.documentMode) {
		var img = new Image();
		img.src = filepath;
		while (true) {
			if (img.fileSize > 0) {
				if (img.fileSize > 5 * 1024 * 1024) {
					layer.msg('图片不能大于5MB',{time:1000});
					return false;
				}
				break;
			}
		}
	} else {
		file_size = obj.files[0].size;
		var size = file_size / 1024;
		if (size > 5120) {
			layer.msg('图片不能大于5MB',{time:1000});
			return false;
		}
	}
	return true;
}


//************************************************上传图片所需的函数END*********************************************************//


/**
 * 通过ajax提交图片
 */
//function ajaxFileUpload(obj) {
//    var lis = $("#image_container").find("li");
//    if (lis.length > 1) {
//        msg("只能上传一张照片");
//        return false;
//    }
//    var id = $(obj).attr("id");
//    $.ajaxFileUpload({
//        url : rootPath + '/uploadFile/uploadOneFile',
//        secureuri : false,
//        fileElementId : id, // input标签id属性值
//        dataType : 'json',
//        success : function(data, status) {
//            if (data.code == 1) {
//                $("#tagIcon").val(data.filePath);
//                var oldLi = "<li>" + "<div class=\"pic1\">" + "<img src=\"" + rootPath
//                        + "/statics/images/upload_pic1.png\" />"
//                        + "<input id=\"tagIcon\" type=\"file\" name=\"tagIcon\" onchange=\"ajaxFileUpload(this)\" />"
//                        + "</div>" + "</li>";
//                var li = "<li>" + " <div class=\"pic1\">" + "     <img src=\"" + imgRootURL + data.filePath + "\" />"
//                        + "     <a id=\"btn_close\" href=\"javascript:void(0)\" class=\"icon_close\"></a>"
//                        + "   </div>" + "</li>";
//                $("#image_container").empty();
//                $("#image_container").append(li);
//                $("#image_container").find("a").each(function() {
//                    $(this).click(function() {
//                        $(this).closest("li").remove();
//                        $("#image_container").append(oldLi);
//                    });
//                });
//            } else {
//                msg("上传失败");
//            }
//        },
//        error : function(data, status, e) {
//            msg("系统异常");
//        }
//    });
//}